package Object.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author haomin
 * @date 2022/11/10 10:57
 **/

public class Test {
    public static void main(String[] args) throws Exception{
        // 得到class
        Class<Son> c1 = Son.class;
        Class<? extends Son> c2 = new Son().getClass();
        Class<?> c3 = Class.forName("Object.reflect.Son");

        System.out.println(c1 == c2);
        System.out.println(c2 == c3);

        // 得到构造方法
        Constructor<?>[] constructors = c1.getConstructors();
        System.out.println(Arrays.toString(constructors));
        Constructor<?>[] declaredConstructors = c1.getDeclaredConstructors();
        System.out.println(Arrays.toString(declaredConstructors));

        // 得到方法
        Method[] methods = c1.getMethods();
        System.out.println(Arrays.toString(methods));
        Method[] declaredMethods = c1.getDeclaredMethods();
        System.out.println(declaredMethods);

        // 得到属性
        Field[] fields = c1.getFields();
        System.out.println(fields);
        Field[] declaredFields = c1.getDeclaredFields();
        System.out.println(declaredFields);

        // 使用反射使用对象私有的构造方法
        Class<?> clSon = Class.forName("Object.reflect.Son");
        Constructor<?> constructor = clSon.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);
        Object hh = constructor.newInstance("hh");
        Son son = (Son) hh;
        System.out.println(son);

        // 使用反射设置对象私有的属性
        Class<Son> sonClass = Son.class;
        Field field = sonClass.getDeclaredField("name");
        field.setAccessible(true);
        Son son1 = sonClass.newInstance();
        field.set(son1, "dd");
        System.out.println(field.get(son1));

        // 使用反射使用对象私有方法
        Class<Son> sonClass1 = Son.class;
        Method method2 = sonClass1.getDeclaredMethod("method2", String.class);
        method2.setAccessible(true);
        Son son2 = sonClass1.newInstance();
        method2.invoke(son2, "李四");
    }
}